import 'dart:convert';

import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:provider/provider.dart';
import 'package:taonile/config/config.dart';

import '../entity/user_info_entity.dart';
import '../http/api.dart';
import '../provider/userinfo_provider.dart';
import '../routers/routers.dart';
import '../views/dialog_manager.dart';

///
/// 修改昵称
///
class MineChangeNickname extends StatefulWidget {
  const MineChangeNickname({Key? key}) : super(key: key);

  @override
  State<MineChangeNickname> createState() => _MineChangeNicknameState();
}

class _MineChangeNicknameState extends State<MineChangeNickname> {
  var _content;

  upUserInfo(Function onSucces) async {
    FocusManager.instance.primaryFocus?.unfocus();
    if (_content == null || _content.isEmpty) {
      EasyLoading.showToast("请输入新昵称");
      return;
    }
    dynamic result = await Api.upUserinfo({'nickname': _content});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      dynamic users = await Api.getUserinfo();
      Map<String, dynamic> resultUsers = Map.from(users);
      UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
      onSucces(infoEntity);
    }
  }

  @override
  Widget build(BuildContext context) {
    UserInfoEntity info = Provider.of<UserInfoProvider>(context).userInfo;
    _content ??= info.data.nickname;
    return Scaffold(
        backgroundColor: Config.colorBg2,
        appBar: AppBar(
          title: const Text('修改昵称'),
          centerTitle: true,
        ),
        body: SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: Container(
            width: double.infinity,
            height: double.infinity,
            margin: EdgeInsets.symmetric(vertical: 30.w, horizontal: 30.w),
            child: Column(
              children: [
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                  decoration: BoxDecoration(
                    color: (Config.colorWhite),
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  child: Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            width: 100.w,
                            child: Text(
                              "昵称",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 520.w,
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 20,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _content = value;
                                });
                              },
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输入新昵称",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                              controller: TextEditingController.fromValue(
                                TextEditingValue(
                                  text: _content,
                                  selection: TextSelection.fromPosition(
                                    TextPosition(
                                        // affinity: TextAffinity.downstream,
                                        offset: _content.length),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 750.w,
                  height: 100.w,
                  padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
                  margin: EdgeInsets.only(top: 45.w),
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () => upUserInfo((UserInfoEntity infoEntity) {
                      Provider.of<UserInfoProvider>(context, listen: false)
                          .changeUserinfo(infoEntity);
                      EasyLoading.showToast("修改成功");
                      Routes.router.pop(context);
                    }),
                    style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                    child: const Text('保存'),
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}
